package queries;

import controller.LollaWrapper;
import entities.Update;
import entities.Updates;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UpdateQueries extends AbstractQueries {
    private long pageCount;
    private final String baseUpdateUrl;
    private final LollaWrapper wrap;

    public UpdateQueries(LollaWrapper wrap) throws
            IOException {
        this.wrap = wrap;
        baseUpdateUrl = wrap.createFullAPIUrl("updates");
        Updates updates = wrap.makeCall(baseUpdateUrl, Updates.class);
        pageCount = updates.getTotalPages();
    }

    private List<Update> getUpdatesByPage(int page)
            throws IOException {
        String url = baseUpdateUrl + "&page=" + page;
        return wrap.makeCall(url, Updates.class).getUpdates();
    }

    public List<Update> getAllUpdates() throws
            IOException {
        List<Update> allUpdates = new ArrayList<Update>();
        for (int i = 1; i <= pageCount; i++) {
            allUpdates.addAll(getUpdatesByPage(i));
        }
        return allUpdates;
    }

    public List<Update> getUpdatesAfterDate(Date date) throws IOException, ParseException {
        List<Update> ret = new ArrayList<Update>();
        int curPage = 1;
        long maxPage = wrap.makeCall(baseUpdateUrl, Updates.class).getTotalPages();
        Boolean needMore = true;
        Boolean go = true;
        List<Update> updates;
        while (go) {
            updates = getUpdatesByPage(curPage);
            curPage++;
            for (Update update : updates) {
                if (date.compareTo(wrap.getUpdatedOnDateFormat().parse(update.getUpdatedOn())) < 0) {
                    ret.add(update);
                } else {
                    needMore = false;
                }
            }
            if (maxPage < curPage || !needMore) {
                go = false;
            }
        }
        return ret;
    }
}
